<?php

class Ext_Buddy_Save
{
    protected $_buddyUserId;
    
    protected $_messager;
    const NOT_LOGIN                              = 'notLogin';
    protected $_messageTemplates = array(
        self::NOT_LOGIN                          => "Please login.",
    );
    protected $_messages = array();
    
    public function __construct($buddyUserId)
    {
        $this->_messager = new Ext_Messager($this->_messageTemplates);
        
        $this->_buddyUserId = $buddyUserId;
    }
    
    public function save($buddy)
    {
        $userId = Ext_Auth_Front::getInstance()->getIdentity();
        
        if(!$userId){
            $this->addMessage($this->_messager->createMessage(self::NOT_LOGIN));
            return false;
        }
        
        $buddyRow = App_Model_DbTable_Buddy::getInstance()->getRowByUserIdBuddyUserId($userId, $this->_buddyUserId);
        if($buddy == 'delete'){
            if($buddyRow){
                App_Model_DbTable_Buddy::getInstance()->del($buddyRow['id']);
            }
        }else{
            if(!$buddyRow){
                $row = array(
                    'userId'             => $userId,
                    'buddyUserId'        => $this->_buddyUserId,
                );
                App_Model_DbTable_Buddy::getInstance()->addNew($row);
            }
        }
        
        return true;
    }
    
    public function addMessage($message)
    {
        $this->_messages[] = $message;
    }
    
    public function addMessages($messages)
    {
        $this->_messages = array_merge($this->_messages, $messages);
    }
    
    public function getMessages()
    {
        return $this->_messages;
    }
}
